package com.example.springboot.controller;

import com.example.springboot.mapper.FruitMapper;
import com.example.springboot.pojo.Fruit;
import com.example.springboot.service.FruitService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class FruitController {
    @Autowired
    private FruitService fruitService;
    
    @GetMapping("/list")
    public String list(Model model){
        List<Fruit> list = fruitService.list();
        model.addAttribute("list",list);
        return  "list";
    }
    
    @GetMapping("/user/{id}")
    public String view(Model model, @PathVariable("id")Long id){
        Fruit fruit =  fruitService.selectById(id);
        model.addAttribute("fruit",fruit);
        return "view";
    }
    
    @GetMapping("/add")
    public String add(Model model){
        return "add";
    }
    @PostMapping("/add")
    public String add(Fruit fruit){
         Integer result =   fruitService.add(fruit);
         
        return "redirect:list";
    }
    @GetMapping("/delete/{id}")
    public String delete( @PathVariable("id")Long id){
        Integer  result =  fruitService.delete(id);
        return "redirect:/list";
    }
    @GetMapping("/update/{id}")
    public String update(Model model, HttpSession session, @PathVariable("id")Long id){
        Fruit  fruit =  fruitService.selectById(id);
        model.addAttribute("fruitUp",fruit);
       session.setAttribute("fruitId",fruit.getFruitId());
        return "/update";
    }
    
    @GetMapping("/update")
    public String update( HttpSession session, Fruit fruit){
        fruit.setFruitId((Long) session.getAttribute("fruitId"));
        Integer  result =  fruitService.update(fruit);
        session.setAttribute("fruitId",fruit.getFruitId());
        return "/update";
    }
}
